package com.hare.harelearn.TempLearn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: HareLearn
 * @description:
 * @author: Hare
 * @create: 2025−05-23 22:36
 * @Version 1.0
 **/
public class 父子结构打印 {

    public static void main(String[] args) {
        List<Node> nodes = new ArrayList<>();
        nodes.add(new Node(1, 0, "AA"));
        nodes.add(new Node(2, 1, "BB"));
        nodes.add(new Node(3, 1, "CC"));
        nodes.add(new Node(4, 3, "DD"));
        nodes.add(new Node(5, 3, "EE"));
        nodes.add(new Node(6, 2, "FF"));
        nodes.add(new Node(7, 2, "GG"));
        nodes.add(new Node(8, 4, "HH"));
        nodes.add(new Node(9, 5, "II"));
        nodes.add(new Node(10, 0, "JJ"));
        nodes.add(new Node(11, 10, "KK"));
        nodes.add(new Node(12, 10, "LL"));
        nodes.add(new Node(13, 13, "MM"));  // 自引用节点
        nodes.add(new Node(14, 13, "NN"));
        nodes.add(new Node(15, 14, "OO"));

        // 打印树形结构
        print(nodes);
    }

    /**
     * 选择排序
     *
     * @param
     */
    static class Node {
        int id;
        int parentId;
        String name;

        public Node(int id, int parentId, String name) {
            this.id = id;
            this.parentId = parentId;
            this.name = name;
        }
    }


    public static void print(List<Node> list) {
        // 构建父节点到子节点的映射
        Map<Integer, List<Node>> parentToChildren = new HashMap<>();

        // 首先将所有节点按父节点分组
        for (Node node : list) {
            parentToChildren.putIfAbsent(node.parentId, new ArrayList<>());
            parentToChildren.get(node.parentId).add(node);
        }

        // 从根节点(parentId=0)开始递归打印
        List<Node> rootNodes = parentToChildren.get(0);
        if (rootNodes != null) {
            for (Node root : rootNodes) {
                printNode(root, 0, parentToChildren);
            }
        }
    }

    private static void printNode(Node node, int level, Map<Integer, List<Node>> parentToChildren) {
        // 根据层级打印缩进
        for (int i = 0; i < level; i++) {
            System.out.print("    ");
        }
        // 打印节点名称
        System.out.println(node.name);

        // 递归打印子节点
        List<Node> children = parentToChildren.get(node.id);
        if (children != null) {
            for (Node child : children) {
                printNode(child, level + 1, parentToChildren);
            }
        }
    }
}
